package RnD;

import Rout.*;
import com.sun.org.omg.SendingContext.CodeBasePackage.URLSeqHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoAlertPresentException;
import org.testng.Assert;
import org.testng.annotations.*;

public class SuperCatcher {

    private GoBefore browser = new GoBefore();
    private ArrayList<String> urls = new ArrayList<String>();
    private int attempt;   // how much we'll try for catch events
    private static String TESTRUN = "\n Run test: ", TESTCASE = "\n\nTest case: ", TESTNAME = "test_", NOTFOUND = "Ads not found";
    private String NextUrl;
    private CsvFileWriter toCsv;
    private String SourceSite;
    private String Referal, openTabs;
    private Map<String, String> map = new HashMap<String, String>(); ;
    private String GEO, BrowserName, OSName;
    private ArrayList<String> newTab;
    private int retryCount;    
    private int agent;
    private int enough;
    private boolean clickmilk;

    @BeforeMethod
    public void setUp() throws Exception {
                     

        map.put("kat.cr", "http://kat.cr/inara-the-jungle-girl-2012-1080p-brrip-x264-yify-t10871176.html");
        map.put("uploaded.net", "http://uploaded.net/file/nqx3bw8k/from/ruwwfn");
        map.put("Videomega.tv", "http://videomega.tv/?ref=RPN8N6UEF77FEU6N8NPR");
        map.put("Thevideos.tv", "http://thevideos.tv/km0aqosuav76.html");
        map.put("Streamcloud.eu", "http://streamcloud.eu/yqx7qmptal1h");
        map.put("Vodlocker.com", "http://vodlocker.com/ojtl9gm6rbq1");
        map.put("shared.sx", "http://shared.sx/0060718775");
        map.put("letitbit.net", "http://letitbit.net/download/a821fb964696/Key-Mail-Hunter.txt.html?lang=en");

        urls.addAll(map.values());
        
        setClickmilk(true);
        
        
        setEnough(2);
        
        agent = 5;
        
        setRetryCount(1);
        setAttempt(3);

//        browser.setXpButton("//div/a");
        System.out.println(TESTRUN + getClass().getSimpleName());
        browser.setXpFilename(null);
        browser.setDetctButton(false);
        browser.setEnableSafeBrow(Boolean.FALSE);
//        browser.setChDrvPath("/home/user/Dropbox/WebDriver/lin64/chromedriver");
//        browser.setRemoteDriver("192.168.5.193"); //Win7Clone VBox
        browser.setRemoteDriver("192.168.4.219"); //Win7x32 VBox
//	
        browser.setTimeToWait(1);
        browser.setNoJavaScript(true);
        System.out.println("Time to wait: " + browser.getTimeToWait());
    }

    public void setUp_via_API(String remoteIP, ArrayList<String> apiurl, String options, int agent, int attempt, boolean clickmilk) throws Exception {
        setRetryCount(1);
        setEnough(2);
        if (!options.isEmpty()) {
            browser.setXpButton(options);
        }
        
        for (String apiurl1 : apiurl) {
            map.put(apiurl1.substring(7, 15), apiurl1);
        }
        
        setClickmilk(clickmilk);
        
        setAttempt(attempt);
        
        this.agent = agent;
        this.urls = apiurl;

        System.out.println(TESTRUN + getClass().getSimpleName());
        System.out.println(urls);
        browser.setXpFilename(null);
        browser.setDetctButton(false);
        browser.setEnableSafeBrow(Boolean.FALSE);
        browser.setTimeToWait(1);
        browser.setNoJavaScript(true);
        if (remoteIP.contains("chromedriver")) {
            browser.setChDrvPath(remoteIP);            
        } else {
            browser.setRemoteDriver(remoteIP);
        } 
        Test();
        Down();
    }

    public void closeAlerts() throws Exception {
        
        for (int i = 0; i < 2; i++) {                    
        int t=1000*i;
        try {            
            System.err.println("try switch to alert");            
            browser.getDriver().switchTo().alert().accept();
            break;                        
        } catch (Exception ex) {
            Thread.sleep(t);
            try {
                System.err.println("try push ENTER");
                browser.getClicker().sendKeys(Keys.ENTER).build().perform(); 
                break;
            } catch (Exception e) {
                Thread.sleep(t);
                       try {
                           System.err.println("js confirm");
                ((JavascriptExecutor) browser.getDriver()).executeScript("window.confirm = function(msg) { return true; }"); 
                break;
            } catch (Exception es) { 
                Thread.sleep(t);
                try {
                    System.err.println("js alert");
                    ((JavascriptExecutor) browser.getDriver()).executeScript("window.alert = function(msg) { return true; }");
                    break;
                    
                } catch (Exception ess) {
                    Thread.sleep(t);
                                      try {                                          
                                          System.err.println("js confirm false");
                        ((JavascriptExecutor) browser.getDriver()).executeScript("window.confirm = function(msg) { return false; }");
                break;
                    } catch (Exception esss) {
                        Thread.sleep(t);
                        try {               
                            System.err.println("js alert false");
                        ((JavascriptExecutor) browser.getDriver()).executeScript("window.alert = function(msg) { return true; }");
                        Thread.sleep(t);
                    } catch (Exception esad) {  
                        Thread.sleep(t);
                            System.err.println("oopps:: " + i);
                    }
                    }                    
                }               
            }
            }
     
        }
        
        Thread.sleep(2000);
        }
    }
    

    @Test //Void Footer Baner
    public void Test() throws Exception {

        

            try {
                browser.getDriver().quit();
            } catch (Exception e) {
            }

            toCsv = new CsvFileWriter(10);
            browser.setUserAg(agent);
            if (agent == 3 || agent == 6) {
                browser.resizeBrowser(460, 840);
            } else {
                browser.setBrowserHeight(0);
            }

            for (Map.Entry<String, String> url : map.entrySet()) {
                SourceSite = url.getKey();
                BrowserName = browser.getUsAgBrName();
                OSName = browser.getUsAgOsName();
                int curTest = (url.getKey().indexOf(url.getKey()) + 1);

                browser.setCurURL(url.getValue());
                System.out.println(TESTCASE + curTest);

//                Thread.sleep(1000000);
                System.out.println("\nTest URL is: " + url.getValue());

                for (int j = 0; j < getRetryCount(); j++) {
                    try {
                        TestIN(url.getValue());
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("second chance: " + j);
                        setRetryCount(retryCount++);
                        if (getRetryCount()==getEnough()) {
                            break;
                        }
                    }
                }
                toCsv.writeCsvFile("CSVs/test_" + "_" + GEO + "_" + BrowserName + OSName + ".csv");

            }
        
//    }
//        browser.getDriver().close();
    }

    @Test
    public void TestIN(String url) throws Exception {
        for (int m = 0; m < attempt; m++) {
            
            
            browser.setUp();
            if (m == 0) {
                GEO = browser.detectGEO();
            }
            browser.setRepDir(TESTNAME + "_" + SourceSite + "_" + BrowserName + "_" + OSName + "_" + GEO);
            browser.setCustomSrcDir("screenshots/" + browser.getRepDir());
            
            

            System.out.println("attempt :" + m);
//                    
            try {                
                browser.getDriver().get(url);                
            } catch (Exception ext) {               
                closeAlerts();
                browser.getDriver().get(url);
            }
            //redirect check
            if (!browser.getDriver().getCurrentUrl().contentEquals(url)) {
                try {
                    System.out.println("redirect catched");
                    browser.getDriver().get(url);
                    browser.getDriver().navigate().refresh();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

//Click on button
            try {
                browser.getXpButton();
                if (!browser.getXpButton().isEmpty() && browser.getXpButton() != null) {
                    System.out.println("Click on button");
                    browser.testRun();
                    Thread.sleep(2000);

                    try {
                        closeAlerts();
                    } catch (Exception e) {
                    }
                }
            } catch (Exception e) {
            }

//Click On Milk
            
            if (clickmilk) {
               Thread.sleep(1000);
            browser.getClicker().moveByOffset(5, 35).click().build().perform();                       
            System.out.println("Click on milk");
            try {
                              
            } catch (Exception e) {
                closeAlerts();  
            }  
            }
           

            newTab = new ArrayList<String>(browser.getDriver().getWindowHandles());

//If 2 tabs present, switch to new tab             
            if (newTab.size() > 1) {
                System.out.print("Open new tab.");
                System.out.println(" Total open tabs is: " + newTab.size());
                for (int i = 1; i < newTab.size(); i++) {
                    System.out.println("Switch to tab # " + i);
                    try {
                        browser.getDriver().switchTo().window(newTab.get(i));
                    } catch (Exception e) {
                        closeAlerts();
                        browser.getDriver().switchTo().window(newTab.get(i));
                    } 

                    
                   
                    try {                                                
                        openTabs = "open_tab:_" + i;
                    } catch (Exception e) {
                       closeAlerts();                       
                       openTabs = "open_tab:_" + i;
                    }
                                        
                    try {                        
                        Referal = (browser.getReferal(browser.getDriver(), NextUrl));
                    } catch (Exception e) {                        
                        closeAlerts();
                        Referal = (browser.getReferal(browser.getDriver(), NextUrl));
                    }
                    
                    try {
                        NextUrl = browser.getDriver().getCurrentUrl();
                    } catch (Exception e) {                       
                        closeAlerts();
                        NextUrl = browser.getDriver().getCurrentUrl();
                     }
                    try {
                        browser.takeFoto();
                    } catch (Exception e) {
                        closeAlerts();
                        browser.takeFoto();
                    }

                    System.out.println("Redirect via URL: " + Referal);
                    System.out.println("!" + browser.getFotoName() + "|thumbnail!");
                    System.out.println(toCsv.createArrayList(SourceSite, GEO, OSName, BrowserName, openTabs, NextUrl, browser.getFotoName(), Referal));
                }
            } else {
                System.out.println(NOTFOUND);                
            }
            browser.setRepDir(null);
            browser.getDriver().quit();
        }
    }

    @AfterMethod
    public void Down() throws Exception {
        setRetryCount(0);
        browser.getDriver().quit();
    }

    public void ForceDown() throws Exception {
        setRetryCount(0);
        browser.getDriver().quit();
    }

    public int getRetryCount() {
        return retryCount;
    }

    public void setRetryCount(int retryCount) {
        this.retryCount = retryCount;
    }

    public int getAttempt() {
        return attempt;
    }

    public void setAttempt(int attempt) {
        this.attempt = attempt;
    }

    private int getEnough() {
        return enough;
    }
    
    private void setEnough(int en){
        this.enough = en;
    }

    public boolean isClickmilk() {
        return clickmilk;
    }

    public void setClickmilk(boolean clickmilk) {
        this.clickmilk = clickmilk;
    }
    


}
